/**
 * 选择账簿
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0002.AccQuery.SelectAccForm", {
  extend: "PSI.AFX.Form.EditForm",

  config: {
    currentCompanyId: null,
    currentYear: null,
    currentMonth: null,
    accNumber: null, // 账簿码
  },

  /**
   * @override
   */
  initComponent() {
    const me = this;

    PCL.apply(me, {
      header: {
        title: me.formatTitle(PSI.Const.PROD_NAME),
        height: 40
      },
      maximized: true,
      layout: "border",
      bodyPadding: 5,
      items: [{
        region: "center",
        layout: {
          type: "hbox",
          align: "stretch",
          margin: 5,
        },
        border: 0,
        items: [
          me.getAccListGrid(),
          {
            xtype: 'panel',
            hidden: true,
            id: me.buildId(me, "panelSubAcc"),
            flex: 1,
            border: 0,
            layout: {
              type: "vbox",
              align: "stretch",
            },
            items: [
              me.getSubAcc01Grid(),
              me.getSubAcc02Grid(),
              me.getSubAcc03Grid(),
            ],
          }
        ]
      }, {
        region: "north",
        height: 45,
        border: 0,
        layout: {
          type: "table",
          columns: 4,
          tableAttrs: PSI.Const.TABLE_LAYOUT,
        },
        items: me.getQueryCmp(),
      }],
      buttons: [{
        text: "确定",
        ...PSI.Const.BTN_STYLE,
        handler: me._onOK,
        scope: me
      }, {
        text: "取消",
        ...PSI.Const.BTN_STYLE,
        handler() {
          me.close();
        },
        scope: me
      }],
      listeners: {
        show: {
          fn: me._onWndShow,
          scope: me
        },
        close: {
          fn: me._onWndClose,
          scope: me
        }
      }
    });

    me.callParent(arguments);

    me.editQueryOrg = PCL.getCmp(me.buildId(me, "editQueryOrg"));
    me.editQueryPeriodYear = PCL.getCmp(me.buildId(me, "editQueryPeriodYear"));
    me.editQueryPeriodMonth = PCL.getCmp(me.buildId(me, "editQueryPeriodMonth"));
    me.editQuerySubject = PCL.getCmp(me.buildId(me, "editQuerySubject"));

    me.panelSubAcc = PCL.getCmp(me.buildId(me, "panelSubAcc"));

    me.editQueryPeriodYear.setValue(me.getCurrentYear());
    me.editQueryPeriodMonth.setValue(me.getCurrentMonth());

    me.queryCompanyList();
  },

  /**
   * @private
   */
  getQueryCmp() {
    const me = this;

    const modelName = me.buildModelName(me, "QueryOrg");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "name"]
    });

    return [{
      border: 0,
      html: `<h2 style='margin:0px'>明细分类账查询 - 选择账簿</h2>`,
    }, {
      id: me.buildId(me, "editQueryOrg"),
      labelWidth: 70,
      width: 490,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "组织机构",
      xtype: "combobox",
      queryMode: "local",
      editable: false,
      valueField: "id",
      displayField: "name",
      store: PCL.create("PCL.data.Store", {
        model: modelName,
        autoLoad: false,
        data: []
      }),
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        },
        select: {
          fn: me._onComboOrgSelect,
          scope: me
        },
      },
      colspan: 2,
    }, {
      id: me.buildId(me, "editQueryPeriod"),
      labelWidth: 70,
      width: 220,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "会计期间",
      xtype: "fieldcontainer",
      layout: "hbox",
      items: [
        {
          xtype: "numberfield",
          hideTrigger: true,
          allowDecimals: false,
          width: 40,
          value: (new Date()).getFullYear(),
          id: me.buildId(me, "editQueryPeriodYear"),
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, { xtype: "displayfield", value: "年", width: 15, }, {
          xtype: "combobox",
          width: 70,
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["id", "text"],
            data: [[1, "一月"], [2, "二月"],
            [3, "三月"], [4, "四月"],
            [5, "五月"], [6, "六月"],
            [7, "七月"], [8, "八月"],
            [9, "九月"], [10, "十月"],
            [11, "十一月"], [12, "十二月"]]
          }),
          valueField: "id",
          displayFIeld: "text",
          queryMode: "local",
          editable: false,
          value: (new Date()).getMonth() + 1,
          id: me.buildId(me, "editQueryPeriodMonth"),
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }
      ],
    }, {
      id: me.buildId(me, "editQuerySubject"),
      labelWidth: 100,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "会计科目码",
      xtype: "textfield",
      listeners: {
        change: {
          fn: me._onSubjectChange,
          scope: me
        }
      }
    }
    ];
  },

  /**
   * @private
   */
  _onWndShow() {
    const me = this;

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMapMain.disable();
    }

    // AFX
    PCL.get(window).on('beforeunload', me.__onWindowBeforeUnload);

  },

  /**
   * @private
   */
  _onWndClose() {
    const me = this;

    // AFX
    PCL.get(window).un('beforeunload', me.__onWindowBeforeUnload);

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMapMain.enable();
    }
  },

  /**
   * @private
   */
  _onOK() {
    const me = this;

    const companyId = me.editQueryOrg.getValue();
    const year = me.editQueryPeriodYear.getValue();
    const month = me.editQueryPeriodMonth.getValue();

    const item = me.getAccListGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择账簿");
      return;
    }
    const level = parseInt(item[0].get("subAccLevel"));

    let accNumber = item[0].get("accNumber");

    let subAccLevel = -1;
    const subAccList = [];
    let subAcc = "";
    let accName = accNumber + " - " + item[0].get("name");

    if (level == 1) {
      const it = me.getSubAcc01Grid().getSelectionModel().getSelection();
      if (it && it.length == 1) {
        const code = it[0].get("code");
        const name = it[0].get("name");

        if (code == "") {
          subAccLevel = -1;
          subAcc = "";
        } else {
          subAccLevel = 1;
          subAcc = code;
          accName += " \\ " + name;

          subAccList.push(subAcc);
        }
      }
    } else if (level == 2) {
      let it = me.getSubAcc01Grid().getSelectionModel().getSelection();
      if (it && it.length == 1) {
        const code = it[0].get("code");
        const name = it[0].get("name");

        if (code == "") {
          subAccLevel = -1;
          subAcc = "";
        } else {
          subAccLevel = 1;
          subAcc = code;
          accName += " \\ " + name;
          subAccList.push(subAcc);

          it = me.getSubAcc02Grid().getSelectionModel().getSelection();
          if (it && it.length == 1) {
            const code2 = it[0].get("code");
            const name2 = it[0].get("name");

            if (code2) {
              subAccLevel = 2;
              subAcc = code2;
              accName += " \\ " + name2;
              subAccList.push(subAcc);
            }
          }
        }
      }
    } else if (level == 3) {
      let it = me.getSubAcc01Grid().getSelectionModel().getSelection();
      if (it && it.length == 1) {
        const code = it[0].get("code");
        const name = it[0].get("name");

        if (code == "") {
          subAccLevel = -1;
          subAcc = "";
        } else {
          subAccLevel = 1;
          subAcc = code;
          accName += " \\ " + name;

          subAccList.push(subAcc);

          it = me.getSubAcc02Grid().getSelectionModel().getSelection();
          if (it && it.length == 1) {
            const code2 = it[0].get("code");
            const name2 = it[0].get("name");

            if (code2) {
              subAccLevel = 2;
              subAcc = code2;
              accName += " \\ " + name2;
              subAccList.push(subAcc);

              it = me.getSubAcc03Grid().getSelectionModel().getSelection();
              if (it && it.length == 1) {
                const code3 = it[0].get("code");
                const name3 = it[0].get("name");
                if (code3) {
                  subAccLevel = 3;
                  subAcc = code3;
                  accName += " \\ " + name3;
                  subAccList.push(subAcc);
                }
              }
            }
          }
        }
      }
    }

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._onSelectAccCallback.apply(parentForm,
        [companyId, year, month, accNumber, subAccLevel, subAccList, accName]);

      me.close();
    }
  },

  /**
   * @private
   */
  queryCompanyList() {
    const me = this;
    const store = me.editQueryOrg.getStore();
    const r = {
      url: me.URL("SLN0002/AccQuery/companyList"),
      callback(options, success, response) {
        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);

          const companyId = me.getCurrentCompanyId();
          if (companyId) {
            me.editQueryOrg.setValue(companyId);
          } else if (data.length > 0) {
            me.editQueryOrg.setValue(data[0]["id"]);
          }

          me.refreshAccListGrid(true);
        }
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   */
  _onSubjectChange() {
    const me = this;

    me.panelSubAcc.hide();

    me.refreshAccListGrid(false);
  },

  /**
   * @private
   */
  getAccListGrid() {
    const me = this;

    if (me._accListGrid) {
      return me._accListGrid;
    }

    const modelName = me.buildModelName(me, "AccList");

    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "accNumber", "name", "subjectCode", "subAccLevel"]
    });

    me._accListGrid = PCL.create("PCL.grid.Panel", {
      flex: 1,
      cls: "PSI-FC",
      header: false,
      border: 1,
      columnLines: true,
      columns: [{
        header: "账簿码",
        dataIndex: "accNumber",
        menuDisabled: true,
        sortable: false,
        width: 100
      }, {
        header: "账簿名称",
        dataIndex: "name",
        width: 300,
        menuDisabled: true,
        sortable: false,
        renderer(value) {
          return me.toAutoWrap(value);
        }
      },],
      store: PCL.create("PCL.data.Store", {
        model: modelName,
        autoLoad: false,
        data: []
      }),
      listeners: {
        select: {
          fn: me._onAccListGridSelect,
          scope: me
        }
      }
    });

    return me._accListGrid;
  },

  /**
   * @private
   */
  _onAccListGridSelect() {
    const me = this;

    me.getSubAcc01Grid().getStore().removeAll();
    me.getSubAcc02Grid().getStore().removeAll();
    me.getSubAcc03Grid().getStore().removeAll();

    const item = me.getAccListGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }
    const level = parseInt(item[0].get("subAccLevel"));

    if (level > 0) {
      me.panelSubAcc.show();
    } else {
      me.panelSubAcc.hide();
    }

    if (level == 1) {
      me.getSubAcc01Grid().show();
      me.getSubAcc02Grid().hide();
      me.getSubAcc03Grid().hide();
    } else if (level == 2) {
      me.getSubAcc01Grid().show();
      me.getSubAcc02Grid().show();
      me.getSubAcc03Grid().hide();
    } else if (level == 3) {
      me.getSubAcc01Grid().show();
      me.getSubAcc02Grid().show();
      me.getSubAcc03Grid().show();
    }

    if (level > 0) {
      me.getSubAcc01Grid().getStore().reload();
    }
  },

  /**
   * @private
   * 
   * @param {boolean} selectRow true的时候，用于会计科目码input输入时候动态刷新Grid 
   */
  refreshAccListGrid(selectRow) {
    const me = this;

    const companyId = me.editQueryOrg.getValue();
    if (!companyId) {
      return;
    }

    const subjectCode = me.editQuerySubject.getValue();

    const el = me.getAccListGrid().getEl();
    const store = me.getAccListGrid().getStore();

    if (selectRow) {
      el?.mask(PSI.Const.LOADING);
    }

    const r = {
      url: me.URL("SLN0002/AccQuery/queryAccList"),
      params: {
        companyId,
        subjectCode,
      },
      callback(options, success, response) {
        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);

          if (store.getCount() > 0) {
            if (selectRow) {
              const accNumber = me.getAccNumber();
              if (accNumber) {
                const r = store.findExact("accNumber", accNumber);
                if (r != -1) {
                  me.getAccListGrid().getSelectionModel().select(r);
                } else {
                  me.getAccListGrid().getSelectionModel().select(0);
                }
              } else {
                me.getAccListGrid().getSelectionModel().select(0);
              }
            } else {
            }
          }
        }

        if (selectRow) {
          el?.unmask();
        }
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   * 
   * 一级子账簿Grid
   */
  getSubAcc01Grid() {
    const me = this;

    if (me._subAcc01Grid) {
      return me._subAcc01Grid;
    }

    const modelName = me.buildModelName(me, "SubAcc01");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["code", "name"]
    });

    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: [],
      pageSize: 100,
      proxy: {
        type: "ajax",
        actionMethods: {
          read: "POST"
        },
        url: me.URL("SLN0002/AccQuery/querySubAcc01"),
        reader: {
          root: 'dataList',
          totalProperty: 'totalCount'
        }
      }
    });
    store.on("beforeload", () => {
      store.proxy.extraParams = me.getQueryParamForQuerySubAcc01();
    });

    me._subAcc01Grid = PCL.create("PCL.grid.Panel", {
      flex: 1,
      margin: "0 0 0 5",
      border: 1,
      cls: "PSI-FC",
      viewConfig: {
        enableTextSelection: true
      },
      tbar: ["->", {
        id: me.buildId(me, "ptbSubAcc01"),
        border: 0,
        xtype: "pagingtoolbar",
        store,
      }, "-", {
          xtype: "displayfield",
          fieldStyle: "font-size:13px",
          value: "每页显示"
        }, {
          id: me.buildId(me, "comboSubAcc01"),
          xtype: "combobox",
          editable: false,
          width: 60,
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["text"],
            data: [["20"], ["50"], ["100"], ["300"],
            ["1000"]]
          }),
          value: 100,
          listeners: {
            change: {
              fn() {
                store.pageSize = PCL.getCmp(me.buildId(me, "comboSubAcc01")).getValue();
                store.currentPage = 1;
                PCL.getCmp(me.buildId(me, "ptbSubAcc01")).doRefresh();
              },
              scope: me
            }
          }
        }, {
          xtype: "displayfield",
          fieldStyle: "font-size:13px",
          value: "条一级子账簿记录"
        }],
      columnLines: true,
      columns: [{
        header: "一级子账簿",
        dataIndex: "name",
        menuDisabled: true,
        sortable: false,
        flex: 1,
      }],
      store,
      listeners: {
        select: {
          fn: me._onSubAcc01GridSelect,
          scope: me
        }
      }
    });

    return me._subAcc01Grid;
  },

  /**
   * @private
   */
  getQueryParamForQuerySubAcc01() {
    const me = this;

    const item = me.getAccListGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const acc = item[0];
    const accNumber = acc.get("accNumber");

    const companyId = me.editQueryOrg.getValue();
    const year = me.editQueryPeriodYear.getValue();
    const month = me.editQueryPeriodMonth.getValue();

    return {
      companyId,
      accNumber,
      year,
      month,
    };
  },

  /**
   * @private
   */
  _onSubAcc01GridSelect() {
    const me = this;

    const item = me.getAccListGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }
    const level = parseInt(item[0].get("subAccLevel"));

    if (level > 1) {
      me.getSubAcc02Grid().getStore().reload();
    }
  },

  /**
   * @private
   */
  getSubAcc02Grid() {
    const me = this;

    if (me._subAcc02Grid) {
      return me._subAcc02Grid;
    }

    const modelName = me.buildModelName(me, "SubAcc02");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["code", "name"]
    });

    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: [],
      pageSize: 100,
      proxy: {
        type: "ajax",
        actionMethods: {
          read: "POST"
        },
        url: me.URL("SLN0002/AccQuery/querySubAcc02"),
        reader: {
          root: 'dataList',
          totalProperty: 'totalCount'
        }
      }
    });
    store.on("beforeload", () => {
      store.proxy.extraParams = me.getQueryParamForQuerySubAcc02();
    });

    me._subAcc02Grid = PCL.create("PCL.grid.Panel", {
      flex: 1,
      margin: "0 0 0 5",
      border: 1,
      cls: "PSI-FC",
      viewConfig: {
        enableTextSelection: true
      },
      tbar: ["->", {
        id: me.buildId(me, "ptbSubAcc02"),
        border: 0,
        xtype: "pagingtoolbar",
        store,
      }, "-", {
          xtype: "displayfield",
          fieldStyle: "font-size:13px",
          value: "每页显示"
        }, {
          id: me.buildId(me, "comboSubAcc02"),
          xtype: "combobox",
          editable: false,
          width: 60,
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["text"],
            data: [["20"], ["50"], ["100"], ["300"],
            ["1000"]]
          }),
          value: 100,
          listeners: {
            change: {
              fn() {
                store.pageSize = PCL.getCmp(me.buildId(me, "comboSubAcc02")).getValue();
                store.currentPage = 1;
                PCL.getCmp(me.buildId(me, "ptbSubAcc02")).doRefresh();
              },
              scope: me
            }
          }
        }, {
          xtype: "displayfield",
          fieldStyle: "font-size:13px",
          value: "条二级子账簿记录"
        }],
      columnLines: true,
      columns: [{
        header: "二级子账簿",
        dataIndex: "name",
        menuDisabled: true,
        sortable: false,
        flex: 1,
      }],
      store,
      listeners: {
        select: {
          fn: me._onSubAcc02GridSelect,
          scope: me
        }
      }
    });

    return me._subAcc02Grid;
  },

  /**
   * @private
   */
  getQueryParamForQuerySubAcc02() {
    const me = this;

    const item = me.getAccListGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const acc = item[0];
    const accNumber = acc.get("accNumber");

    const companyId = me.editQueryOrg.getValue();
    const year = me.editQueryPeriodYear.getValue();
    const month = me.editQueryPeriodMonth.getValue();

    const it = me.getSubAcc01Grid().getSelectionModel().getSelection();
    let subAcc01 = undefined;
    if (item == null || item.length != 1) {
      subAcc01 = "";;
    }
    subAcc01 = it[0].get("code");

    return {
      companyId,
      accNumber,
      year,
      month,
      subAcc01,
    };
  },

  /**
   * @private
   */
  _onSubAcc02GridSelect() {
    const me = this;

    const item = me.getAccListGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }
    const level = parseInt(item[0].get("subAccLevel"));

    if (level > 2) {
      me.getSubAcc03Grid().getStore().reload();
    }
  },

  /**
   * @private
   */
  getSubAcc03Grid() {
    const me = this;

    if (me._subAcc03Grid) {
      return me._subAcc03Grid;
    }

    const modelName = me.buildModelName(me, "SubAcc03");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["code", "name"]
    });

    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: [],
      pageSize: 100,
      proxy: {
        type: "ajax",
        actionMethods: {
          read: "POST"
        },
        url: me.URL("SLN0002/AccQuery/querySubAcc03"),
        reader: {
          root: 'dataList',
          totalProperty: 'totalCount'
        }
      }
    });
    store.on("beforeload", () => {
      store.proxy.extraParams = me.getQueryParamForQuerySubAcc03();
    });

    me._subAcc03Grid = PCL.create("PCL.grid.Panel", {
      flex: 1,
      margin: "0 0 0 5",
      border: 1,
      cls: "PSI-FC",
      viewConfig: {
        enableTextSelection: true
      },
      tbar: ["->", {
        id: me.buildId(me, "ptbSubAcc03"),
        border: 0,
        xtype: "pagingtoolbar",
        store,
      }, "-", {
          xtype: "displayfield",
          fieldStyle: "font-size:13px",
          value: "每页显示"
        }, {
          id: me.buildId(me, "comboSubAcc03"),
          xtype: "combobox",
          editable: false,
          width: 60,
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["text"],
            data: [["20"], ["50"], ["100"], ["300"],
            ["1000"]]
          }),
          value: 100,
          listeners: {
            change: {
              fn() {
                store.pageSize = PCL.getCmp(me.buildId(me, "comboSubAcc03")).getValue();
                store.currentPage = 1;
                PCL.getCmp(me.buildId(me, "ptbSubAcc03")).doRefresh();
              },
              scope: me
            }
          }
        }, {
          xtype: "displayfield",
          fieldStyle: "font-size:13px",
          value: "条三级子账簿记录"
        }],
      columnLines: true,
      columns: [{
        header: "三级子账簿",
        dataIndex: "name",
        menuDisabled: true,
        sortable: false,
        flex: 1,
      }],
      store,
      listeners: {
        select: {
          fn: me._onSubAcc03GridSelect,
          scope: me
        }
      }
    });

    return me._subAcc03Grid;
  },

  /**
   * @private
   */
  getQueryParamForQuerySubAcc03() {
    const me = this;

    const item = me.getAccListGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const acc = item[0];
    const accNumber = acc.get("accNumber");

    const companyId = me.editQueryOrg.getValue();
    const year = me.editQueryPeriodYear.getValue();
    const month = me.editQueryPeriodMonth.getValue();

    const it = me.getSubAcc02Grid().getSelectionModel().getSelection();
    let subAcc02 = undefined;
    if (item == null || item.length != 1) {
      subAcc02 = "";;
    }
    subAcc02 = it[0].get("code");

    return {
      companyId,
      accNumber,
      year,
      month,
      subAcc02,
    };
  },

  /**
   * @private
   */
  _onComboOrgSelect() {
    const me = this;

    me.refreshAccListGrid(false);
  }
});
